﻿using Autofac;
using CSRedis;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using SH.Common;
using SH.Common.CommonReturn;
using SH.Multitenant.Application.IServices.IUser;
using System.Collections;
using System.Collections.Generic;


namespace SH.Multitenant.API.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly IUserServices _userServices;
        private readonly CSRedisClient _redis;
        private readonly IMemoryCache _cache;

        public UserController(IUserServices userServices, IMemoryCache cache)
        {

            _userServices = userServices;
            _redis = AppService.AutofacContainer.Resolve<CSRedisClient>();
            _cache = cache;
        }

        //[HttpGet]
        //public IActionResult GetUsers()
        //{
        //    var result = _userServices.All.ToList();
        //    return Ok(result);
        //}
        /// <summary>
        /// 租户登录
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> UserLogin(LoginRequestDTO request)
        {
            if (request == null)
            {
                return BadRequest();
            }
            if (string.IsNullOrEmpty(request.UName))
            {
                return BadRequest();
            }
            if (string.IsNullOrEmpty(request.UPwd))
            {
                return BadRequest();
            }
            var result = await _userServices.UserLogin(request);
            if (result.Code == 200)
            {
                var token = result.Data!.Token;
                Response.Headers["token"] = token;
                Response.Headers["Access-Control-Expose-Headers"] = "token";
                //redis用户账号
                _redis.Set("uName", result.Data.UName);
                _redis.Set("tenantId", result.Data.TenantId);
                //存储用户token作为后台访问验证
                _cache.Set("token", token);
            }
            return Ok(result);
        }


    }
}
